import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Input, Select, Button, message } from "antd";
import { updateArticle, getArticleDetail } from "../../../api/articles";
import { useParams } from "react-router-dom";

const { Option } = Select;

const EditArticle: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { id } = useParams<{ id: string }>();
  console.log("11", useParams);

  if (!id) {
    throw new Error("文章ID不存在");
  } // 确保id存在
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchArticle = async () => {
      try {
        setLoading(true);
        const res = await getArticleDetail(id!); // 非空断言，确保id存在
        form.setFieldsValue({
          title: res.data.title,
          category: res.data.category,
          tags: res.data.tags,
          content: res.data.content,
        });
      } catch (error) {
        message.error("获取文章详情失败");
      } finally {
        setLoading(false);
      }
    };
    fetchArticle();
  }, [id, form]);

  const onFinish = async (values: any) => {
    const userId = localStorage.getItem("userId") || ""; // 处理null情况，初始化为空字符串
    if (!userId) {
      message.error("用户未登录，请重新登录");
      return;
    }
    try {
      await updateArticle(id!, { ...values, userId }); // 非空断言，确保id存在
      message.success("文章修改成功");
    } catch (error) {
      message.error("文章修改失败");
    }
  };

  return (
    <div>
      <h2>编辑文章</h2>
      <Form form={form} onFinish={onFinish} layout="vertical">
        <Form.Item name="title" label="标题" rules={[{ required: true }]}>
          <Input placeholder="请输入标题" />
        </Form.Item>
        <Form.Item name="category" label="分类" rules={[{ required: true }]}>
          <Select placeholder="请选择分类">
            <Option value="技术">技术</Option>
            <Option value="生活">生活</Option>
            <Option value="其他">其他</Option>
          </Select>
        </Form.Item>
        <Form.Item name="tags" label="标签" rules={[{ required: true }]}>
          <Input placeholder="请输入标签（用逗号分隔）" />
        </Form.Item>
        <Form.Item name="content" label="内容" rules={[{ required: true }]}>
          <Input.TextArea rows={6} placeholder="请输入内容" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            保存修改
          </Button>
          <Button
            type="default"
            onClick={() => navigate(-1)}
            style={{ marginBottom: 16, marginRight: 16 }}
          >
            返回
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default EditArticle;